﻿from System import *
from System.Windows import *
from System.Windows.Threading import *
from System.Windows.Media import *
from System.Net import *
from System.Text import *
from System.Collections import *
from System.Collections.Specialized import *
from System.Windows.Media.Imaging import *
from System.Diagnostics import *
from System.Text.RegularExpressions import *

LoadAssembly("System.Json")

#import clr
#clr.AddReference("System.Json")
#from System.Json import *


URLS = {
		"auth" : "http://twitter.com/account/verify_credentials.json",
		"friends" : "http://twitter.com/statuses/friends_timeline.json",
		"update" : "http://twitter.com/statuses/update.json",
		"search" : "http://search.twitter.com/search.json"
}

keyword = "gestalt"

#tweets = [{"name":"Gestalt", "image_url":"http://assets0.twitter.com/images/twitter.png", "text":"loading tweets. Click buttons to read more!", "created_at":DateTime.Now.ToShortDateString(), "source":"gestalt"}]
tweets = [{"name":"", "image_url":"", "text":"", "created_at":"", "source":"", "id":""}]
current_tweet = -1
qs = None

class Twitter:
	""" I deal with talking to Twitter. """
	def __init__(self):
	    self.hash = ""
	    self.presenters = []

	def credentials(username, password):
	    utf8 = UTF8Encoding();
	    self.hash = Convert.ToBase64String(utf8.GetBytes("%s:%s" % (username,password)))

	def add_presenter(self, presenter_instance):
	    self.presenters.append(presenter_instance)

	def friends_timeline(self):
		""" I get your friends' update """
		url = "%s" % URLS["friends"]
		self.fetch(url)

	def update(self, msg):
		""" I make updates for you. """
		url = "%s?status=%s" % (URLS["update"], msg)
		self.fetch(url, "POST")

	def search(self, query_terms, query_string=None):
	    """ Search for anything you want. I'll find it. You choose how to use the results. """
	    url = URLS["search"]
	    if(query_string):
	        url += query_string
	    else:
	        url += "?q=" + query_terms
	    self.fetch(url)

	def update_status_list(self, sender, args):
		if (args.Error == None):
			resp = JsonValue.Parse(args.Result)
			for presenter in self.presenters:
				presenter.add_to_status_list(resp)
		else:
			log(args.Error)

	def fetch(self, uri, method="GET"):
		client = WebClient()
		
		client.DownloadStringAsync(Uri(uri))
		
		client.DownloadStringCompleted += self.update_status_list

class BadgePresenter():
    def add_to_status_list(self, json):
        global qs
        qs = json.refresh_url
        #log(json.results)
        tweets.Clear()
        for status in json.results:
            tweets.append({"name":status.from_user, "image_url":status.profile_image_url.Replace("\\",""), "text":status.text, "created_at":DateTime.Parse(status.created_at).ToShortDateString(), "source":status.source, "id":status.id})
        go_to_next_tweet(None, None) #trigger immediately
                    
def ping_twitter(sender, args):
    twitter.search(None, "?tag=" + keyword)
    log("called %s" % DateTime.Now.ToString())

def move_next(sender, args):
    go_to_next_tweet(sender, args)

def go_to_next_tweet(sender, args):
    global current_tweet
    if(current_tweet < len(tweets)-1):
        current_tweet += 1
    else:
        current_tweet = 0
    update_ui(tweets[current_tweet])

def go_to_previous_tweet(sender, args):
    global current_tweet
    if(current_tweet >= 1):
        current_tweet -= 1
    else:
        current_tweet = len(tweets)-1
    update_ui(tweets[current_tweet])

def update_ui(data_hash):
    me.badge.fade_out.Begin()
    me.status.Text = Regex.Unescape(data_hash["text"])
    #me.details.Text = "from %s on %s from %s" % (data_hash["name"], data_hash["created_at"], data_hash["source"])
    
    if data_hash["name"] != "":
        me.details.Text = "from %s on %s" % (data_hash["name"], data_hash["created_at"])
        
    imageUrl = data_hash["image_url"]
    
    if imageUrl.Contains(".gif"):
        me.Loading.Visibility = Visibility.Collapsed
    
    if imageUrl.Contains(".gif") or imageUrl == "":
        imageUrl = "http://assets0.twitter.com/images/twitter.png"
    else:
        me.Loading.Visibility = Visibility.Collapsed
    
    if data_hash.has_key('id'):
        url = "http://www.twitter.com/" + data_hash["name"] + "/statuses/" + data_hash["id"].ToString()
        me.MainRect.DataContext = url
        log(url)
		
    me.avatar.Source = BitmapImage(Uri(imageUrl))
    
    me.badge.fade_in.Begin()
    
def mouse_enter(sender, e):
    sender.Fill = SolidColorBrush(Color.FromArgb(0xFF,0xC5,0xE6,0xF9))

def mouse_leave(sender, e):
    sender.Fill = SolidColorBrush(Color.FromArgb(0xFF,0xD4,0xE9,0xF5))

def browse(sender, e):
    url = me.MainRect.DataContext
    if url != "http://www.twitter.com//statuses/":
        HtmlPage.Window.Navigate(Uri(url), "_blank");

def log(msg):
    #document.msg.innerHTML = "<p>"+str(msg)+"</p>"
    Debug.WriteLine(str(msg))
    
twitter = Twitter()
twitter.add_presenter(BadgePresenter())
twitter.search(None, "?tag=" + keyword)


ping_timer = DispatcherTimer(Interval = TimeSpan(0, 0, 0, 120, 0))
ping_timer.Tick += ping_twitter
ping_timer.Start()

cross_fader = DispatcherTimer(Interval = TimeSpan(0, 0, 0, 10, 0))
cross_fader.Tick += move_next
cross_fader.Start()

me.next.MouseLeftButtonDown += go_to_next_tweet
me.next.MouseEnter +=  mouse_enter
me.next.MouseLeave +=  mouse_leave

me.previous.MouseLeftButtonDown += go_to_previous_tweet
me.previous.MouseEnter +=  mouse_enter
me.previous.MouseLeave +=  mouse_leave

me.MainRect.MouseLeftButtonDown +=  browse
me.MainRect.MouseEnter +=  mouse_enter
me.MainRect.MouseLeave +=  mouse_leave
